import axios from "axios";
import qs from "qs";
import store from "../store";
import router from '../router/index'
import { MessageBox, CreateElement } from 'element-ui';

const service = axios.create({
  timeout: 20000
});

service.defaults.headers.common["Content-Type"] = "application/json";

service.interceptors.request.use(
  config => {
    // 全局加上 Token
    if (store.getters.getToken != "") {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["KY-TOKEN"] = store.getters.getToken;
    }

    if (
      config.method === "post" &&
      config.headers["Content-Type"] === "application/x-www-form-urlencoded"
    ) {
      config.data = qs.stringify(config.data);
    }
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code == undefined && res.status != 200) {
      console.log(response);
    }
    else if (res.code == 20000 ) {
      return res;
    }
    // if the custom code is not 20000, it is judged as an error.
    else {
      
      if (res.code == 4000) {
        Notiflix.Notify.Failure(res.message);
        return res;
      }

      if (res.code == 5000) {
        Notiflix.Notify.Warning(res.message);
        return res;
      }

      if (res.code == 6000) {
        Notiflix.Notify.Info(res.message);
        return res;
      }

      if (res.code == 4001) {
        Notiflix.Report.Failure( '失败', res.message, '好的' );
        return res;
      }

      if (res.code == 5001) {
        Notiflix.Report.Warning( '警告', res.message, '好的' );
        return res;
      }

      if (res.code == 6001) {
        Notiflix.Report.Info( '提示', res.message, '好的' );
        return res;
      }

      if (res.code === 7000) {
        // to re-login

        Notiflix.Confirm.Show( '您的登录权限验证失败', '要重新登录吗?', '重新登录', '取消', function(){ alert('好的'); } ); 
      }
      return res;
      // return Promise.reject(new Error(res.message || "Error"));
    }
  },
  error => {
    if (error == 'Error: Request failed with status code 401') {
      Notiflix.Report.Failure( '先登录吧', '没有账号先注册哦', '好的' );
      router.push({name:'login'});
    }
    else {
      console.error(Promise.reject(error))
      Notiflix.Report.Failure( '服务器异常', '请稍后再试', '好的' );
    }
    const res = {
      code: 500,
      message: '系统异常'
    }
    return res;
  }
);

export default service;
